package net.sashag.nadlandroid;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.DialogInterface.OnMultiChoiceClickListener;
import android.util.Log;
import android.widget.Toast;

import com.googlecode.androidannotations.annotations.Background;
import com.googlecode.androidannotations.annotations.EBean;
import com.googlecode.androidannotations.annotations.RootContext;
import com.googlecode.androidannotations.annotations.UiThread;
import com.parse.ParseException;
import com.parse.PushService;

@EBean
public class RegionSubscribeDialog {
	
	@RootContext protected Context context;
	
	private ProgressDialog progress;
	private Map<String, Region> regions;
	
	@UiThread
	protected void initProgress() {
		progress = new ProgressDialog(context);
		progress.setTitle("Please Wait");
		progress.setMessage("Retrieving regions from our Web service...");
		progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		progress.setCancelable(false);
		progress.show();
	}
	
	@Background
	public void show() {
		initProgress();
		try {
			Region[] allRegions = Region.getAllRegions();
			regions = new HashMap<String, Region>();
			for (Region region : allRegions) {
				regions.put(region.getName(), region);
			}
			showDialog();
		} catch (ParseException e) {
			showError(e.getMessage());
		}
	}
	
	@UiThread
	protected void showError(String error) {
		progress.dismiss();
		Toast.makeText(context, "Error retrieving regions: " + error, Toast.LENGTH_LONG).show();
	}
	
	@UiThread
	protected void showDialog() {
		progress.dismiss();
		
		final String[] regionNames = regions.keySet().toArray(new String[regions.size()]);
		final boolean[] checkedRegions = new boolean[regions.size()];
		final Set<String> existingSubscriptions = PushService.getSubscriptions(context); 
		for (String subscription : existingSubscriptions) {
			int indexOfRegion = Arrays.asList(regionNames).indexOf(subscription);
			if (indexOfRegion != -1)
				checkedRegions[indexOfRegion] = true;
		}
		
		new AlertDialog.Builder(context)
			.setTitle("Choose Regions")
			.setCancelable(true)
			.setMultiChoiceItems(regionNames, checkedRegions, new OnMultiChoiceClickListener() {
				public void onClick(DialogInterface dialog, int which, boolean isChecked) {
					Log.v("RegionSubscribeDialog", "Region " + regionNames[which] + ", checked = " + isChecked);
				}
			})
			.setPositiveButton("Submit", new OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					for (int i = 0; i < checkedRegions.length; ++i) {
						String channel = regionNames[i];
						if (!checkedRegions[i] && existingSubscriptions.contains(channel)) {
							PushService.unsubscribe(context, channel);
							Log.i("RegionSubscribeDialog", "Unsubscribed from channel " + channel);
						}
						if (checkedRegions[i] && !existingSubscriptions.contains(channel)) {
							//We don't provide a more specific activity here, because the push will
							//not cause an activity to launch -- we will display our own notification
							//that will launch the ApartmentDetailsActivity with the newly added apartment.
							PushService.subscribe(context, channel, NadlandroidActivity_.class);
							Log.i("RegionSubscribeDialog", "Subscribed to channel " + channel);
						}
					}
				}
			})
			.setNegativeButton("Cancel", new OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {}
			})
			.show();
	}
	
}
